using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Publicuse.Entity;

namespace Publicuse.Util
{
  public static class ParamsUtil
  {
    /// <summary>
    /// 获取参数值
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static string GetParams(this HttpContext context)
    {
      try
      {
        HttpRequest request = context.Request;
        string data = string.Empty;
        switch (request.Method)
        {
          case "POST":
            if (context.Request.ContentType == "application/json")
            {
              Stream straem = context.Request.HttpContext.Request.Body;
              Encoding encoding = Encoding.UTF8;
              StreamReader reader = new StreamReader(straem, encoding);
              {
                reader.BaseStream.Seek(0, SeekOrigin.Begin);
                var readerStr = reader.ReadToEndAsync().Result;
                reader.BaseStream.Seek(0, SeekOrigin.Begin);
                var postdatalist = JsonUtil.JsonToDictionaryString(readerStr);
                if (postdatalist.Count > 0)
                {
                  data = JsonUtil.ToJson(postdatalist);
                }
              }
            }
            break;
          case "GET":
            var querydata = context.Request.QueryString.ToString();
            NameValueCollection form = HttpUtility.ParseQueryString(querydata);
            //第一步：取出所有get参数
            IDictionary<string, string> parameters = new Dictionary<string, string>();
            for (int f = 0; f < form.Count; f++)
            {
              string key = form.Keys[f];
              parameters.Add(key, form[key]);
            }

            // 第二步：把字典按Key的字母顺序排序
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(
              parameters
            );
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

            // 第三步：把所有参数名和参数值串在一起
            StringBuilder query = new StringBuilder();
            while (dem.MoveNext())
            {
              string key = dem.Current.Key;
              string value = dem.Current.Value;
              if (!string.IsNullOrEmpty(key))
              {
                query.Append(key).Append("=").Append(value).Append("&");
              }
            }
            data = query.ToString().TrimEnd('&');
            break;
          default:
            data = string.Empty;

            break;
        }
        return data;
      }
      catch (Exception ex)
      {
        return string.Empty;
      }
    }
  }
}
